<template>
  <div>
    <a-upload
      :file-list="fileList"
      :remove="handleRemove"
      :before-upload="beforeUpload"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
    >
      <a-button> <a-icon type="upload" /> 选择文件 </a-button>
    </a-upload>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <a-button v-if="hasPermission('addDept')" type="primary" @click="setTableDataSource">
          1.导入Excel
        </a-button>
        <a-button v-if="hasPermission('addDept')" type="primary" @click="handleCreate">
          2.保存数据
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              auth: 'editDept',
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
              auth: 'delDept',
            },
          ]"
        />
      </template>
    </BasicTable>
    <Modal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';

  import { TeacherList, TeacherDel } from '/@/api/teacher/teacher';
  import { useModal } from '/@/components/Modal';
  import Modal from './Modal.vue';

  import { columns, searchFormSchema } from './schema.data';
  import { usePermission } from '/@/hooks/web/usePermission';
  import XLSX, { WorkSheet } from "xlsx";


  export default defineComponent({
    name: 'TeacherExcelManagement',
    components: { BasicTable, Modal, TableAction},
    setup() {
      const { hasPermission } = usePermission();
      const showAction = hasPermission('editDept') || hasPermission('delDept');
      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload, expandAll, setTableData }] = useTable({
        title: '从Excel批量导入教师信息',
        dataSource: [
          {
            id: '001',
            fName: 'malaoshi',
          },
        ],
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        isTreeTable: true,
        pagination: false,
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
          ifShow: showAction,
        },
      });

      function setTableDataSource() {
        setTableData([]);
      }

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        TeacherDel(record.id).then(() => {
          reload();
        });
      }

      function handleSuccess() {
        reload();
      }
      function onFetchSuccess() {
        nextTick(expandAll);
      }
      function readFile(file: File) {
        return new Promise((resolve) => {
          let reader = new FileReader();
          reader.readAsBinaryString(file);
          reader.onload = (ev) => {
            resolve(ev.target?.result);
          };
        });
      }
      async function readExcelFile(file: File, sheetIndex: number) {
        let data = await readFile(file);
        let workbook = XLSX.read(data, { type: 'binary' });
        let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
        data = XLSX.utils.sheet_to_json(worksheet);
        return data;
      }
      function beforeUpload(file: File) {
        let data = readExcelFile(file, 0);
        data.then((d) => {
          //读取文件数据
          console.log(d);
        });
        return false;
      }

      var fileList = [];
      return {
        registerTable,
        registerModal,
        handleCreate,
        setTableDataSource,
        handleEdit,
        handleDelete,
        handleSuccess,
        hasPermission,
        onFetchSuccess,
        beforeUpload,
        fileList,
      };
    },
  });
</script>
